package uy.com.nfc.localassigner.retry;

import java.util.LinkedList;

import uy.com.nfc.localassigner.NFCReceiver;
import android.annotation.SuppressLint;
import android.os.AsyncTask;

import com.example.nfctagcommons.server.ServerConnector;

@SuppressLint("NewApi")
public class RetryQueue {
	public static final Object lock = new Object();
	static final LinkedList<RetryElement> queue = new LinkedList<RetryElement>();
	private static boolean isRunning;
	private static AsyncTask<Void, Void, Void> retryThread;
	
	public static void addRetry(String guardId, String localId, String comments, long time){
		RetryElement retryElement = new RetryElement();
		retryElement.guardId = guardId;
		retryElement.pointId = localId;
		retryElement.comments = comments;
		retryElement.time = time;
		synchronized (lock) {
			queue.add(retryElement);
			if (!isRunning){
				retryThread = new RetryThreadImpl();
				isRunning = true;
    			if (android.os.Build.VERSION.SDK_INT > 10) {
    				retryThread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    			}else{
    				retryThread.execute();
    			}
			}
		}
	}
	
}
class RetryThreadImpl extends AsyncTask<Void, Void, Void>{
	@Override
	protected Void doInBackground(Void... arg0) {
		while (true){
			LinkedList<RetryElement> tempQueue = new LinkedList<RetryElement>();
			synchronized (RetryQueue.lock) {
				while (!RetryQueue.queue.isEmpty()){
					RetryElement retryElement = RetryQueue.queue.removeFirst();
					String guardId = retryElement.guardId;
					String localId = retryElement.pointId;
					String comments = retryElement.comments;
					long time = retryElement.time;
					try { 
						boolean success = ServerConnector.setLocalChecked(NFCReceiver.instance, guardId, localId,comments, time);
						if (!success){
							tempQueue.add(retryElement);
						}
					} catch (Exception e) {
						e.printStackTrace();
						tempQueue.add(retryElement);
					}
				}
			}
			for (RetryElement retryElement : tempQueue){
				RetryQueue.addRetry(retryElement.guardId, retryElement.pointId, retryElement.comments, retryElement.time);
			}
			try {
				Thread.sleep(5000);//Retry every 5 seconds
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}	
}
class RetryElement{
	String guardId;
	String pointId;
	String comments;
	long time;
}
